//
//  HourlyForecastCollectionViewCell.swift
//  SwiftWeather
//
//  Created by shen on 2023/8/28.
//

import UIKit
import Combine

final class HourlyForecastCollectionViewCellViewModel {
    // MARK: Properties

    var numberOfRows: Int {
        hours?.count ?? 0
    }

    private let hours: [Hour]?
    private let temperatureUnits: TemperatureUnits

    // MARK: - Initialization

    init(hours: [Hour]?, temperatureUnits: TemperatureUnits) {
        self.hours = hours
        self.temperatureUnits = temperatureUnits
    }

    func viewModelForCell(at indexPath: IndexPath) -> HourlyForecastCellViewModel {
        return HourlyForecastCellViewModel(
            hour: hours?[indexPath.row],
            temperatureUnits: temperatureUnits
        )
    }
}

class HourlyForecastCollectionViewCell: BaseCollectionViewCell, ViewModelable {
    typealias ViewModel = HourlyForecastCollectionViewCellViewModel

    // MARK: Properties

    var viewModel: ViewModel! {
        didSet {
            weatherTableView.reloadData()
        }
    }

    // MARK: - Views

    private lazy var weatherTableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.allowsSelection = false
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.sf.register(cellWithClass: HourlyForecastTableViewCell.self)
        return tableView
    }()

    // MARK: - Methods

    override func configureAppearance() {
        backgroundColor = Resources.Colors.secondaryBackground
    }

    override func setupViews() {
        weatherTableView.dataSource = self
        weatherTableView.delegate = self
        contentView.addSubview(weatherTableView, useAutoLayout: true)
    }

    override func constraintViews() {
        NSLayoutConstraint.activate([
            weatherTableView.topAnchor.constraint(equalTo: contentView.topAnchor),
            weatherTableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            weatherTableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            weatherTableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
        ])
    }
}

// MARK: - UITableViewDataSource & UITableViewDelegate

extension HourlyForecastCollectionViewCell: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        viewModel != nil ? viewModel.numberOfRows : 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.sf.dequeueReusableCell(withClass: HourlyForecastTableViewCell.self)
        cell.viewModel = viewModel.viewModelForCell(at: indexPath)
        cell.layoutIfNeeded()
        return cell
    }
}
